package com.quxuecx.springcloud.ld.impl;

import com.quxuecx.springcloud.ld.ILoadBalancer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;

/**
 * @author: shaofeer
 * <p>
 * @qq: 337081267
 * <p>
 * @CSDN: http://blog.csdn.net/pyfysf
 * <p>
 * @blog: http://wintp.top
 * <p>
 * @email: shaofeer@163.com
 * <p>
 * @time: 2020/6/28Q
 */
//@Component
@Slf4j
public class MyLoadBalancer implements ILoadBalancer {
    @Autowired
    DiscoveryClient mDiscoveryClient;

    private AtomicInteger mAtomicInteger = new AtomicInteger(0);


    private final int getIndex() {
        int current;
        int next;
        for (; ; ) {
            current = this.mAtomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;

            if (this.mAtomicInteger.compareAndSet(current, next)) {
                System.out.println("*******第几次访问，次数next: " + next);
                return next;
            }
        }
    }

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstances) {
        return serviceInstances.get(getIndex() % serviceInstances.size());
    }


    //private AtomicInteger atomicInteger = new AtomicInteger(0);
    //
    ////坐标
    //private final int getAndIncrement(){
    //    int current;
    //    int next;
    //    do {
    //        current = this.atomicInteger.get();
    //        next = current >= 2147483647 ? 0 : current + 1;
    //    }while (!this.atomicInteger.compareAndSet(current,next));  //第一个参数是期望值，第二个参数是修改值是
    //    System.out.println("*******第几次访问，次数next: "+next);
    //    return next;
    //}
    //
    //@Override
    //public ServiceInstance instances(List<ServiceInstance> serviceInstances) {  //得到机器的列表
    //    int index = getAndIncrement() % serviceInstances.size(); //得到服务器的下标位置
    //    return serviceInstances.get(index);
    //}
}
